package ar.edu.caece.compiler.grammar.factories;

import ar.edu.caece.compiler.grammar.AbstractTokenVisitorFactory;
import ar.edu.caece.compiler.grammar.Recognizer;
import ar.edu.caece.compiler.grammar.TokenRecognizer;
import ar.edu.caece.compiler.grammar.TokenVisitor;
import ar.edu.caece.compiler.grammar.nonterminals.EXPR2A;
import ar.edu.caece.compiler.grammar.nonterminals.EXPRA;
import ar.edu.caece.compiler.grammar.nonterminals.POSP;

public class POSPFactory extends AbstractTokenVisitorFactory {

	private static POSPFactory INSTANCE;
	
	private EXPR2AFactory expr2aFactory;
	private EXPRAFactory expraFactory;
	private TokenVisitor parseEXPR2A;
	private TokenVisitor parseEXPRA;
	
	public static POSPFactory getInstance() throws Exception {
		if(INSTANCE==null) INSTANCE = new POSPFactory();
		return INSTANCE;
	}

	private Initializer initializer = new Initializer() {
		
		@Override
		public void init() throws Exception {
			initializer = NoOperationInitializer.getInstance();
			expr2aFactory = EXPR2AFactory.getInstance();
			expraFactory = EXPRAFactory.getInstance();
			parseEXPR2A = expr2aFactory.makeVisitor();
			parseEXPRA = expraFactory.makeVisitor();
		}
	};

	@Override
	public TokenVisitor makeChainedVisitor(
			final TokenVisitor siguiente) throws Exception {
		initializer.init();

		return new TokenVisitor() {

			@Override
			public Recognizer defaultCase(TokenRecognizer llamador)
					throws Exception {
				TokenVisitor parser = expr2aFactory.makeChainedVisitor(siguiente);
				parser.setInheretedAttributes(getAttributes());
				Recognizer result = llamador.execute(parser);
				if(result instanceof EXPR2A) {
					return new POSP ((EXPR2A) result, (EXPRA) nextToken().execute(parseEXPRA)); 
				} 
				else {
					return result;
				}
			}
			
		};
	
	}
	@Override
	public TokenVisitor makeVisitor() throws Exception {
		initializer.init();

		return new TokenVisitor() {

			@Override
			public Recognizer defaultCase(TokenRecognizer llamador)
					throws Exception {
					return new POSP ((EXPR2A) llamador.execute(parseEXPR2A), (EXPRA) nextToken().execute(parseEXPRA)); 
			}
		};
	}
	
	
}
